﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookExchange.ODataService; 
using BookExchange.Utility;
using BookExchange.Business;
using System.Text;
using System.Net.Mail;
using BookExchange.CustomClass.Base;

namespace BookExchange
{
    public partial class PasswordRecovery : BasePage
    {
        MemberBusiness memberBusiness; 
        const byte LENGTHCODE = 6;

        static Member member;
        static StringBuilder code;


        public PasswordRecovery()
        {
            memberBusiness = new MemberBusiness(); 
        }

        protected void Page_Load(object sender, EventArgs e)
        { 
         }  

        public bool Sending(string from_address, string from_password,
        string from_displayName, string to_address,
        string subject, String body)
        {

            MailMessage msg = new MailMessage();
            msg.To.Add(to_address);
            msg.From = new MailAddress(from_address, from_displayName,
            System.Text.Encoding.UTF8);
            msg.Subject = subject;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = body;
            msg.BodyEncoding = System.Text.Encoding.UTF8; 
            msg.IsBodyHtml = true; 
            msg.Priority = MailPriority.High;

            // Confirm username + password  
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential
            (from_address, from_password);
            // Gate 587 of server SMTP Google to send mail 
            client.Port = MailConfiguration.ServerPort;
            // server address SMTP of google  
            client.Host = MailConfiguration.Host;
            // Use code SSL (Secure Sockets Layer) 
            client.EnableSsl = true;
            // Start send mail  
            try
            {
                client.Send(msg);  //--Send mail--
            }
            catch
            { 
                return false; 
            }
            return true; 

        }

        private StringBuilder GenerationCode()
        { 
            const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

            StringBuilder randomSeries = new StringBuilder();
            Random rand = new Random();

            for (int i = 0; i < LENGTHCODE; i++)
            {
                //Get  random characters from the array of chars 
                string str = chars[rand.Next(chars.Length)].ToString();
                randomSeries.Append(str); 
            }

            return randomSeries;
        }

        protected void PasswordRecovery_Click(object sender, EventArgs e)
        {
            if (MultiView1.ActiveViewIndex == 0)
            { 
                //generation code
                code = GenerationCode();

                //mailsending
                MailSending(code);
            }
            else if (MultiView1.ActiveViewIndex == 1)
            { 
                //Confirmation
                if (code != null)
                {
                    if (code.ToString().Equals(txtCodeConfirmation.Text))
                    {
                        btnNext.Text = "Hoàn thành";
                        MultiView1.ActiveViewIndex = 2;
                    } 
                    else 
                        Response.Write("<script>alert('" + MailConfiguration.WrongVerificationMessage + "');</script>"); 
                }        
            }

            else
            {
                //Set new password
                SetNewPassword();

                //finish
                Response.Write("<script>alert('" + MailConfiguration.SuccessMessage + @"');
                                        window.location = 'Login.aspx';</script>"); 
            }
        }

        void SetNewPassword()
        {   
            //Update new password and save 
            if (member == null)
            {
                Response.Write("<script>alert('" + MailConfiguration.ErrorExceptionMessage + @"');
                                        window.location = 'Default.aspx';</script>");
            }
            else
            {
                member.Password = txtNewPassword.Text;
                memberBusiness.UpdateMember(member); 
            }
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            RedirectToHomepage();
        }


        void MailSending(StringBuilder code)
        {

            MailConfiguration config = new MailConfiguration();
            string username = txtUsername.Text;
            string email = txtEmail.Text;
             member = memberBusiness.GetMemberByUsernameAndEmail(username, email);
            if (member != null)
            {
                if (Sending(MailConfiguration.MailAddress, MailConfiguration.PasswordMailAdress, 
                    MailConfiguration.MailDisplayName, email, MailConfiguration.MailSubject, config.GetBody(username,code).ToString()))
                {
                    MultiView1.ActiveViewIndex = 1;
                    
                }
                else
                    Response.Write("<script>alert('" + MailConfiguration.SendingErrorMessage + "');</script>  ");
            }
            else
                Response.Write("<script>alert('" + MailConfiguration.WrongUsernameMessage + "'); </script>");
            
        }
         

    }
}